<template>
  <div class="online-content">
    <div class="online-box">
      <div class="message-list" ref="msgList">
        <div ref="msgBox" style="padding-bottom: 40px">
          <div
            v-for="(msg, index) in messages.list"
            :key="index"
            :class="['box-bubble', msg.flow]"
            :id="`msg-${index}`"
            style="padding: 0 12px"
          >
            <img
              style="
                border-radius: 50%;
                overflow: hidden;
                background: rgb(192, 192, 192);
              "
              width="40"
              height="40"
              :src="msg.avatar"
              :alt="msg.nick"
            />

            <div
              v-if="msg.type === 'TIMTextElem'"
              :class="['bubble', msg.flow]"
            >
              <div
                style="word-break: break-all; padding: 10px"
                v-html="msg.payload.text"
              ></div>
            </div>

            <div
              v-if="msg.type === 'TIMImageElem'"
              :class="['bubble', msg.flow]"
            >
              <img
                @click="previewImage([msg.payload.imageInfoArray[0].imageUrl])"
                width="100"
                :src="msg.payload.imageInfoArray[0].imageUrl"
              />
            </div>

            <div
              v-if="msg.type === 'TIMVideoFileElem'"
              :class="['bubble', msg.flow]"
            >
              <video controls width="100" :src="msg.payload.videoUrl">
                <source :src="msg.payload.videoUrl" />
              </video>
            </div>
            <!-- 文件 -->
            <div
              v-if="msg.type === 'TIMFileElem'"
              :class="['bubble', msg.flow]"
            >
              <div class="fileBox">
                <span>
                  {{ msg.flow === "in" ? "接收的文件" : "发送的文件" }}:
                  <span
                    class="downEl"
                    @click="
                      handleDownFile(msg.payload.fileUrl, msg.payload.fileName)
                    "
                    >下载</span
                  ></span
                >
                {{ msg.payload.fileName }}
              </div>
            </div>
            <!-- 音频 -->
            <div
              v-if="msg.type === 'TIMSoundElem'"
              :class="['bubble', msg.flow]"
            >
              <audio controls width="100" :src="msg.payload.url">
                <source :src="msg.payload.url" />
              </audio>
            </div>
            <div
              v-if="msg.type === 'TIMCustomElem'"
              @click="viewDetail(msg)"
              :class="['bubble', msg.flow]"
            >
              <div class="chufang-head">
                <img
                  width="68"
                  height="27"
                  src="../../assets/images/kaichufang.png"
                  alt=""
                />
                <div class="show-chufang">查看处方</div>
              </div>

              <p class="chufang-title">{{ msg.payload.data }}</p>
            </div>
          </div>
        </div>
      </div>
      <Divider />

      <div class="form-box">
        <div class="icon_box">
          <Icon
            @click="chooseFile('Video')"
            type="ios-videocam-outline"
            size="22"
          />

          <Icon
            @click="chooseFile('Image')"
            type="ios-image-outline"
            size="22"
          />
          <Icon
            @click="handleChooseFile"
            type="ios-folder-outline

"
            size="22"
          />
        </div>
        <Input
          @keydown.native="enterSubmit"
          v-model="messages.currentMsg"
          type="textarea"
          :rows="6"
          placeholder="请输入内容"
        />
        <Button @click="sendMsg" type="primary" class="save_btn">发送</Button>
      </div>
    </div>
    <input
      ref="chooseImage"
      accept="image/*"
      @change="changeFile"
      type="file"
      hidden
    />
    <input
      ref="chooseVideo"
      accept="video/*"
      @change="changeFile"
      type="file"
      hidden
    />
    <input ref="chooseFile" @change="handleChangeFile" type="file" hidden />
    <Footer :top="20"></Footer>
  </div>
</template>
<script>
import Footer from "@/components/footer/my_footer.vue";
import request, { buyerUrl } from "../../plugins/request";
import { EVENT, TYPES } from "@/plugins/tim/tim-js";

export default {
  components: { Footer },
  data() {
    return {
      imgUrl: require("../../assets/login/student-2.png"),
      fileType: "",
      messages: {
        currentMsg: "",
        list: [],
        nextReqMessageID: "",
      },
    };
  },
  beforeDestroy() {
    this.$tim.logout();
  },
  mounted() {
    request({
      url: buyerUrl + "/buyer/order/userConsult/createIMAccount",
      needToken: true,
    }).then(({ result }) => {
      const { id: userID, userSig } = result;
      this.$tim.login({ userID, userSig });
    });

    this.$tim.on(EVENT.SDK_READY, () => {
      // console.log(this.messages.list,'SDK_READY');
      this.messages.list.length || this.getMessageList({ isInit: true });
      //  this.getMessageList();
    });

    this.$tim.on(EVENT.MESSAGE_RECEIVED, ({ data }) => {
      /*   console.log('🚀🚀','MESSAGE_RECEIVED');
      this.messages.list.push(...data);
      this.$refs.msgBox && (this.$refs.msgList.scrollTop = 999999999)*/
      const userID = window.location.search.split("=")[1];
      [...data].forEach((message) => {
        if (message.from === userID) {
          this.messages.list.push(message);
          this.$refs.msgList.scrollTop = 9999999999;
        }
      });
    });
  },
  methods: {
    previewImage(imgs) {
      open(imgs[0], "new", "location=no, toolbar=no");
    },
    viewDetail({ payload }) {
      const { data: title, description, extension } = payload;
      const content = `<div style="word-break: break-all;">${description}</div>${
        extension &&
        extension
          .split(",")
          .map(
            (href) =>
              `<a style="display: block; word-break: break-all; margin: 10px;" href="${href}">${href}</a>`
          )
      }`;

      this.$Modal.info({ title, content });
    },
    enterSubmit(e) {
      if (e.key === "Enter") {
        if (e.ctrlKey || e.metaKey) {
          this.messages.currentMsg += "\n";
          return;
        }
        e.preventDefault();
        this.sendMsg();
      }
    },
    handleDownFile(url, name) {
      const link = document.createElement("A");
      fetch(url)
        .then((res) => res.blob())
        .then((blob) => {
          link.href = URL.createObjectURL(blob);
          link.download = name;
          document.body.appendChild(link);
          link.click();
          link.remove();
        });
    },
    handleChooseFile() {
      this.$refs.chooseFile.click();
    },
    handleChangeFile(e) {
      const message = this.$tim.createFileMessage({
        to: this.$route.query.user_id,
        conversationType: TYPES.CONV_C2C,
        payload: { file: e.target },
        onProgress(event) {
          console.log("file uploading:", event);
        },
      });
      this.$tim
        .sendMessage(message)
        .then(({ data }) => {
          this.messages.list.push(data.message);
        })
        .catch((imError) => {
          // 发送失败
          console.warn("sendMessage error:", imError);
        });
    },
    changeFile(e) {
      const message = this.$tim[`create${this.fileType}Message`]({
        to: this.$route.query.user_id,
        conversationType: TYPES.CONV_C2C,
        payload: { file: e.target },
        onProgress(event) {
          console.log("file uploading:", event);
        },
      });
      this.$tim
        .sendMessage(message)
        .then(({ data }) => {
          this.messages.list.push(data.message);
        })
        .catch((imError) => {
          // 发送失败
          console.warn("sendMessage error:", imError);
        });
    },

    chooseFile(type) {
      this.fileType = type;
      this.$refs[`choose${type}`].click();
    },
    getMessageList({ isInit = false }) {
      isInit && (this.messages.nextReqMessageID = null);
      this.$tim
        .getMessageList({
          conversationID: `C2C${this.$route.query.user_id}`,
          nextReqMessageID: this.messages.nextReqMessageID,
        })
        .then(({ data }) => {
          console.log("🚀🚀", "getMessageList", "data", data);
          this.messages.list = [
            ...data.messageList,
            ...(isInit ? [] : this.messages.list),
          ];
          this.messages.nextReqMessageID = data.nextReqMessageID;
          //   console.log('🚀🚀',data.messageList.length,'data.messageList');
          // 第一次问诊就把患者的基本信息发给医生
          if (data.messageList.length <= 0) {
            // 获取上一页传来的基础数据，第一次问诊时给医生发送基本信息
            const query = this.$route.query;
            const name = query.name;
            const sex = query.sex == 1 ? "男" : "女";
            const content = query.text;
            this.messages.currentMsg = `姓名：${name};<br>性别：${sex};<br>${content}`;
            if (query.imgList) {
              const imgs = query.imgList.split(",").map((it) => {
                return `<div><img src="${it}"/></div>`;
              });
              this.messages.currentMsg = `姓名：${name};<br>性别：${sex};<br>${content};${imgs.join(
                ","
              )}`;
            }
            this.sendMsg();
            return;
          }
          this.$nextTick(() => {
            this.$refs.msgBox &&
              (this.$refs.msgList.scrollTop = this.$refs.msgBox.offsetHeight);
          });
        })
        .catch((err) => console.log(err));
    },
    sendMsg() {
      if (!this.messages.currentMsg) return;

      let message = this.$tim.createTextMessage({
        to: this.$route.query.user_id,
        conversationType: TYPES.CONV_C2C,
        payload: {
          text: this.messages.currentMsg,
        },
      });

      this.$tim
        .sendMessage(message)
        .then(({ data }) => {
          this.messages.list.push(data.message);
          this.$nextTick(() => {
            this.$refs.msgBox && (this.$refs.msgList.scrollTop = 999999999);
            // this.$refs.msgList.scrollTop = this.$refs.msgBox.offsetHeight;
          });
        })
        .catch((imError) => {
          console.warn("sendMessage error:", imError);
        });

      this.messages.currentMsg = "";
    },
  },
};
</script>

<style lang="scss" scoped>
.fileBox {
  width: 200px;
  height: 100px;
  display: flex;
  flex-direction: column;
  padding: 5px;

  .downEl {
    color: #176eff;
    cursor: pointer;
  }
}

.online-content {
  position: relative;

  .online-box {
    position: relative;
    width: 70%;
    margin: 50px auto;
    border: 1px solid #e3e3e3;
    border-radius: 10px;
    background: #fff;
  }

  .form-box {
    position: relative;

    .icon_box {
      display: flex;
      align-items: center;
      justify-content: space-evenly;
      width: 100px;
      padding: 10px;
    }

    .save_btn {
      position: absolute;
      right: 20px;
      bottom: 20px;
    }
  }

  .message-list {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    overflow-y: auto;
    padding: 15px;
    height: 50vh;

    .box-bubble {
      display: flex;
      align-items: flex-start;
      margin-bottom: 24px;

      &.in {
        justify-content: left;
      }

      &.out {
        justify-content: right;
        flex-direction: row-reverse;
      }

      .bubble {
        display: flex;
        flex-direction: column;
        position: relative;
        overflow: hidden;
        max-width: 100%;
        margin-left: 52px;
        margin-right: 12px;
        font-size: 13px;
        color: #333;
        background-color: #f5f5f5;

        &.in {
          margin-right: 52px;
          margin-left: 12px;
          border-radius: 0 6px 6px 6px;
        }

        &.out {
          margin-left: 52px;
          margin-right: 12px;
          border-radius: 6px 0 6px 6px;
        }

        .chufang-head {
          padding: 10px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          background-color: #2375ff;

          .show-chufang {
            cursor: pointer;
            padding: 0 9px;
            line-height: 2;
            border: 1px solid #fff;
            color: #fff;
            border-radius: 9px;
          }
        }

        .chufang-title {
          width: 220px;
          padding: 10px;
          color: #176eff;
        }
      }
    }
  }
}
</style>
